import React, { useState, useEffect, useRef } from 'react';
import Taro from '@tarojs/taro';
import { View, Image } from '@tarojs/components';
import { Button, Input, Form, FormItem, ImagePreview, Dialog,Radio, ConfigProvider, Steps, Step, Checkbox } from '@nutui/nutui-react-taro';
import carBook from '@/assets/carBook.png';
import getBook from '@/assets/form.png';
import business from '@/assets/business1.png';
import AuthUtil from '../../utils/api/auth'; // 确保引入你的上传工具
import { startEid } from '../../..//mp_ecard_sdk/main';

import { Close } from '@nutui/icons-react-taro'; // 引入关闭图标
import './index.less';

function PersonInfo() {
  const [ownerSignUrl, setOwnerSignUrl] = useState('');
  const [visible1, setVisible1] = useState(false)
  const [checked] = useState(false)
  const [signatureImage, setSignatureImage] = useState<string | null>(null);
  const [agree, setAgree] = useState<string | null>(null);
  const [role, setRole] = useState('company'); // 默认角色为个人
  const [businessLicenseImage, setBusinessLicenseImage] = useState<string | null>(null);
  const [willingness, setWillingness] = useState<string | null>(null);
  const [vehicleRegistration, setVehicleRegistration] = useState<string | null>(null);
  const [images, setImages] = useState<string[]>([]); // 这里指定了类型为字符串数组
  const [showPreview, setShowPreview] = useState(false)
  const [formattedData, setFormattedData] = useState({
    plateNumber: '',
    vehicleIdentificationNumber: '',
    engineNumber: '',
    brandModel: '',
    vehicleType: '',
    ratedCapacity: 0,
    realName: '',
    identityNumber: '',
    contactAddress: '',

    vehicleRegistrationCertificateFront: '',
    vehicleRegistrationCertificateBack: '',


    vehicleRegistration: '',

    sellerType: '',
    signatureImage: ''
  });

  const instance = Taro.getCurrentInstance();
  const formData = instance?.router?.params?.formData;
  const params = formData ? JSON.parse(formData) : {};
  const type = instance?.router?.params?.type;

  useEffect(() => {
    setRole(type);

    setFormattedData(prev => ({ ...prev, ...params, sellerType: type })); // 合并初始数据
  }, []);



  const jumpToSign = () => {
    setVisible1(false)
    const eventKey = 'signatureCompleted'; // 固定事件名称
    Taro.eventCenter.once(eventKey, data => {
      setOwnerSignUrl(data.url);
      uploadFile(data.url, 'signatureImage');

    });
    Taro.navigateTo({ url: `/pages/sign/index?type=${eventKey}` });
  }
  const submitFailed = (error) => {
    // 错误处理逻辑
  };

  const extractBirthDate = (idCard) => {
    // 正则表达式匹配身份证号码中的出生日期
    const regex = /(\d{6})(\d{8})(\d{3})/; // 6位地区码 + 8位出生日期 + 3位顺序码
    const match = idCard.match(regex);

    if (match) {
      const birthDate = match[2]; // 获取出生日期部分
      const year = birthDate.substring(0, 4); // 前4位为年份
      const month = parseInt(birthDate.substring(4, 6), 10); // 第5、6位为月份
      const day = parseInt(birthDate.substring(6, 8), 10); // 第7、8位为日期

      // 格式化输出
      return `${year}/${month}/${day}`;
    }
    return '';
  };
  const fetchEidResult = async (token, value) => {
    const formData = {
      eidToken: token
    }

    const response = await AuthUtil.EidResult(formData);

    if (response.Text) {
      const eidResult = response;// 假设返回的数据就是 eid result
      const idInfo = extractBirthDate(formattedData.identityNumber)
      console.log('EID Result:', eidResult.Text, idInfo);
      if (eidResult.Text.ErrMsg === "本次流程未完成") {
        return Taro.showToast({
          title: eidResult.Text.ErrMsg,
          icon: 'none',
        })
      }
      if (idInfo === eidResult.Text.OcrBirth) {
        submitSucceed(value)
      } else {
        Taro.showToast({
          title: '身份证信息不一致',
          icon: 'none',

        })
      }

    }

  };

  const goSDK = (token, value) => {
    startEid({
      data: {
        token,
      },
      verifyDoneCallback(res) {
        const { token, verifyDone } = res;
        if (verifyDone) {
          fetchEidResult(token, value)
        } else {
          Taro.showToast({
            title: '核身失败',
            icon: 'none',
          })
        }
        console.log('收到核身完成的res:', res);
        console.log('核身的token是:', token);
        console.log('是否完成核身:', verifyDone);
      },
    });
  }
  const showToast = (title) => {
    Taro.showToast({ title, icon: 'none' });
  };
  const fetchEidToken = async (value) => {
    if (!agree) return Taro.showToast({ title: '请先同意用户服务协议和隐私保护声明', icon: 'none' });
    if (!ownerSignUrl) return Taro.showToast({ title: '请先签名在进行人脸核验', icon: 'none' });


    try {
      const response = await AuthUtil.EidToken();

      if (response.EidToken) {
        const eidToken = response.EidToken; // 假设返回的数据就是 eid token
        console.log('EID Token:', eidToken);
        goSDK(eidToken, value);
      } else {
        showToast('获取 EID Token 失败');
      }
    } catch (error) {
      console.error('请求 EID Token 失败:', error);
      Taro.showToast({
        title: '请求 EID Token 失败',
        icon: 'none',
      });
    }
  };

  const submitSucceed = async (values) => {
    if (role === 'company') {
      if (!businessLicenseImage) {
        Taro.showToast({ title: '请上传营业执照', icon: 'none' });
        return; // 终止提交
      }
      if (!willingness) {
        Taro.showToast({ title: '请上传授权委托书', icon: 'none' });
        return; // 终止提交
      }
    }

    const { data } = await AuthUtil.editForm(formattedData, params.id);
    console.log(data, "data");
    if (data) {
      // 使用本地存储暂存数据
      Taro.setStorageSync('formData', JSON.stringify(formattedData));
      Taro.navigateTo({ url: '/pages/summary/index' });
    } else {
      Taro.showToast({ title: '网络异常,请稍后再试', icon: 'none' });
    }
  };

  const handleImageSelect = (setType: (url: string) => void, type: string) => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const imagePath = res.tempFiles[0].path;
        setType(imagePath); // 更新图片路径
        uploadFile(imagePath, type);
      },
      fail: (err) => {
        console.error('选择图片失败', err);
        Taro.showToast({ title: '选择图片失败', icon: 'none' });
      }
    });
  };

  const handleClear = (type: string) => {
    if (type === 'businessLicenseImage') {
      setBusinessLicenseImage(null);
    } else if (type === 'willingness') {
      setWillingness(null);
    } else if (type === 'vehicleRegistration') {
      setVehicleRegistration(null);
    }
  };

  const updateFormattedData = (key: string, value: string) => {
    setFormattedData(prevData => ({
      ...prevData,
      [key]: value
    }));
  };

  const uploadFile = (filePath, type) => {
    Taro.uploadFile({
      url: 'https://car-admin.xipeisoft.com/api/upload',
      filePath: filePath,
      name: 'files',
      header: {
        Authorization: `Bearer ${Taro.getStorageSync('token')}`,
      },
    }).then(res => {
      if (res.data.length !== 0) {
        const imageData = JSON.parse(res.data)[0];
        const imagePath = imageData.url;
        const imageId = imageData.id;
        if (type === 'businessLicenseImage') {
          // setBusinessLicenseImage(imagePath);
          updateFormattedData('businessLicenseImage', imageId);
        } else if (type === 'willingness') {
          // setWillingness(imagePath);
          updateFormattedData('willingness', imageId);
        } else if (type === 'vehicleRegistration') {
          // setVehicleRegistration(imagePath);
          updateFormattedData('vehicleRegistration', imageId);
        } else {
          updateFormattedData('signatureImage', imageId);
          // setSignUrl
        }
      }
    });
  };
  const handleImage = (value) => {
    setImages([{ src: value }])
    setShowPreview(true)
  }
  const handleAgreedToPrivacyChange = (e) => {
    setAgree(e)
    // setAgreedToPrivacy(e.target.value === 'true');
  };
  const customTheme = {
    nutuiStepsBaseLineWidth: '70%',
    nutuiStepsProcessIconBgColor: '#3768FA',
    nutuiStepsProcessIconColor: '#fff',
    nutuiStepsProcessTitleColor: '#3768FA',
    nutuiStepsProcessTitleFontSize: '15px',
    nutuiStepsProcessTitleFontWeight: '500',
    nutuiStepsFinishIconColor: '#3768FA',
    nutuiStepsFinishTitleColor: '#3768FA',
    nutuiStepsFinishLineBackground: '#3768FA',
  }
  return (
    <View className="person_license">
      <ConfigProvider theme={customTheme}>
        <Steps value={2}>
          <Step value={1} title="步骤一" />
          <Step value={2} title="步骤二" />
        </Steps>
      </ConfigProvider>
      <Form
        onFinish={(values) => fetchEidToken(values)}
        onFinishFailed={submitFailed}
        footer={
          <div style={{ display: 'flex', justifyContent: 'center', width: '100%' }}>
            <Button className="form_buttom" nativeType="reset">重置</Button>
            <Button className="form_buttom" nativeType="submit" type="primary" style={{ marginLeft: '20px', background: "#009afa" }}>
              提交
            </Button>
          </div>
        }
      >
        <FormItem label="过户主体" name="role">
          <Input defaultValue={type === 'person' ? "个人" : "公司"} disabled type="text" />
        </FormItem>

        {role === 'company' && (
          <>
            <FormItem label="营业执照" name="businessLicenseImage">
              {businessLicenseImage ? (
                <View className='driving_img'>
                  <div className="clear_btn" onClick={() => handleClear('businessLicenseImage')}><Close /></div>
                  <Image className='car_info' onClick={() => { handleImage(businessLicenseImage) }} src={businessLicenseImage} />
                </View>
              ) : (
                <View className='driving_img' onClick={() => handleImageSelect(setBusinessLicenseImage, 'businessLicenseImage')}>
                  <Image className='car_info' src={business} />
                  <div className='driving_name'>上传营业执照</div>
                </View>
              )}
            </FormItem>

            <FormItem label="授权委托书" name="willingness">
              {willingness ? (
                <View className='driving_img'>
                  <div className="clear_btn" onClick={() => handleClear('willingness')}><Close /></div>
                  <Image className='car_info' onClick={() => { handleImage(willingness) }} src={willingness} />
                </View>
              ) : (
                <View className='driving_img' onClick={() => handleImageSelect(setWillingness, 'willingness')}>
                  <Image className='car_info' src={business} />
                  <div className='driving_name'>上传授权委托书</div>
                </View>
              )}
            </FormItem>
            <FormItem label="机动车登记证" name="vehicleRegistration">
              {vehicleRegistration ? (
                <View className='driving_img'>
                  <div className="clear_btn" onClick={() => handleClear('vehicleRegistration')}><Close /></div>
                  <Image className='car_info' onClick={() => { handleImage(vehicleRegistration) }} src={vehicleRegistration} />
                </View>
              ) : (
                <View className='driving_img' onClick={() => handleImageSelect(setVehicleRegistration, 'vehicleRegistration')}>
                  <Image className='car_info' src={business} />
                  <div className='driving_name'>上传机动车登记证</div>
                </View>
              )}
            </FormItem>
          </>
        )}
        {role === 'person' && (
          <>
            <FormItem label="机动车登记证" name="vehicleRegistration">
              {vehicleRegistration ? (
                <View className='driving_img'>
                  <div className="clear_btn" onClick={() => handleClear('vehicleRegistration')}><Close /></div>
                  <Image className='car_info' onClick={() => { handleImage(vehicleRegistration) }} src={vehicleRegistration} />
                </View>
              ) : (
                <View className='driving_img' onClick={() => handleImageSelect(setVehicleRegistration, 'vehicleRegistration')}>
                  <Image className='car_info' src={business} />
                  <div className='driving_name'>上传机动车登记证</div>
                </View>
              )}
            </FormItem>
          </>
        )}
        <FormItem label="签名" name="role">
          <View>
            {ownerSignUrl
              ? <Image src={ownerSignUrl} onClick={() => jumpToSign()} style={{ width: '200px' }} />
              : <div onClick={() => setVisible1(true)}>点击签名</div>
            }

          </View>
          {/* <div>
            特别注意：
          </div>
          <div>
            请确保由{params.realName}本人在此页面签字并提交，他人不得代签，否则产生的一切法律责任由代签人承担!
          </div>
          <div>
            核验后如未提交签名，则视为本次核验任务未完成，可能影响后续业务办理。
          </div> */}
        </FormItem>
      </Form>

      <div style={{ marginLeft: '20px' }}>

        <Radio.Group onChange={handleAgreedToPrivacyChange}>
          <Radio value="1">
            <div className='select_radio'>
              <div>
                我已阅读并同意
              </div>
              <div className='user' onClick={() => { Taro.navigateTo({ url: `/pages/role/index` }); }}>
                《用户服务协议》
              </div>
              及
              <div className='user' onClick={() => { Taro.navigateTo({ url: `/pages/privacy/index` }); }}>
                《隐私保护声明》
              </div>
            </div>

          </Radio>
        </Radio.Group>
      </div>
      <Dialog
        title="温馨提示"
        visible={visible1}
        onConfirm={() => jumpToSign()}
        onCancel={() => setVisible1(false)}
      >
        请确保由{params.realName}本人在此页面签字并提交，他人不得代签，否则产生的一切法律责任由代签人承担!
      </Dialog>
      <ImagePreview
        autoPlay
        images={images}
        closeIcon
        visible={showPreview}
        onClose={() => setShowPreview(false)}
        indicator
      />
    </View>
  );
}

export default PersonInfo;